<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        img{width:40px;}
        .number{width:40px;}
    </style>
</head>
<body>
    <table border="1" width=600 align="center">
        <thead>
            <tr>
                <th>选中</th>
                <th>图片</th>
                <th>名称</th>
                <th>数量</th>
                <th>价格</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            
        </tbody>
        <tfoot>
            <tr>
                <td align="right"><input id="allCheck" type="checkbox"></td>
                <td><label for="allCheck">全选</label></td>
                <td align="right">总数量：</td>
                <td>0</td>
                <td align="right">总价：</td>
                <td>0</td>
                <td>删除选中</td>
            </tr>
        </tfoot>
    </table>
</body>
<script src="./ajax.js"></script>
<script>

    class Cart{
        constructor(){
            this.tbody = document.querySelector("tbody");
            // 商品数据接口：用来获取单条商品详细信息
            this.url = "http://localhost:3000/getGoods";
            // 获取本地存储的购物车数据
            this.getLocalData();
            // 获取服务器商品详细数据
            this.getGoodsData();
        }
        getLocalData(){
            const goods = localStorage.getItem("goods");
            this.goods = goods ? JSON.parse(goods) : [];
        }
        getGoodsData(){
            const arr = [];
            // 根据本地存储中的商品id，发起商品详情数据请求
            this.goods.forEach(val=>{
                arr.push(ajax({
                    url:this.url,
                    data:{
                        id:val.id
                    }
                }))
            })
            // 借助promise的批处理，获取所有数据
            Promise.all(arr).then(res=>{
                let str = "";
                // 遍历
                res.forEach((val, idx)=>{
                    // 解析
                    const msg = JSON.parse(val).data[0];
                    // 拼接
                    str += `<tr>
                        <td align="right"><input type="checkbox" class="check" ${this.goods[idx].check ? 'checked' : '' }></td>
                        <td><img src="${msg.goodsImg}" alt=""></td>
                        <td>${msg.goodsName}</td>
                        <td><input type="number" class="number" value="${this.goods[idx].num}"></td>
                        <td>${this.goods[idx].price}</td>
                        <td>${(this.goods[idx].price * this.goods[idx].num).toFixed(2)}</td>
                        <td>删除</td>
                    </tr>`
                })
                // 设置到页面
                this.tbody.innerHTML = str;
            })
        }
    }

    new Cart;


    
    
</script>
</html>